const db = require('../db/index')

// 导入处理路径的 path 核心模块
const path = require('path')

// 引入支付宝配置文件
const alipaySdk = require('../payment/alipayUtil')
const AlipayFormData = require('alipay-sdk/lib/form').default;

//引入axiso
const axios = require('axios');

// 添加结算列表处理函数
exports.addOrder = (req, res) => {

    let goodsArr = Object.keys(req.body)

    //生成订单号order_id，规则：时间戳 + 7为随机数
    function setTimeDateFmt(s) {
        return s < 10 ? "0" + s : s;
    }
    function randomNumber() {
        const now = new Date();
        let month = now.getMonth() + 1;
        let day = now.getDate();
        let hour = now.getHours();
        let minutes = now.getMinutes();
        let seconds = now.getSeconds();
        month = setTimeDateFmt(month);
        day = setTimeDateFmt(day);
        hour = setTimeDateFmt(hour);
        minutes = setTimeDateFmt(minutes);
        seconds = setTimeDateFmt(seconds);
        let orderCode =
            now.getFullYear().toString() +
            month.toString() +
            day +
            hour +
            minutes +
            seconds +
            Math.round(Math.random() * 1000000).toString();
        return orderCode;
    }

    //商品列表名称
    let goodsName = [];
    //订单商品总金额
    let goodsPrice = 0;
    //订单商品总数量
    let goodsNum = 0;
    //订单号
    let orderId = randomNumber();


    goodsArr.forEach(v => {
        v = JSON.parse(v)
        v.forEach(v => {
            goodsName.push(v.name);
            goodsPrice += v.price * v.num;
            goodsNum += parseInt(v.num);
        })
    })

    db.query(`insert into submitorder (name,price,num,state,orderId) values ('${goodsName}','${goodsPrice}','${goodsNum}','1','${orderId}')`, function () {

        db.query(`select * from submitorder where orderId='${orderId}'`, function (err, result) {
            res.send({
                data: {
                    success: true,
                    code: 200,
                    data: result
                }
            })
        })
    })


    // let orderList = []
    let orderImgurl = []
    // let orderPrice = 0
    let orderName = []
    // let orderNum = 0
    let orderState = []
    goodsArr.forEach(v => {
        v = JSON.parse(v)
        // orderList = v
        v.forEach(v => {
            orderName.push(v.name)
            orderImgurl.push(v.imgUrl)
            orderState.push(v.state)
        })

    })

    db.query('delete from addorder', req.params.id, (err, results) => {
        // if (err) return res.cc(err)

        db.query('select * from addorder', req.params.id, (err, results) => {
            // if (err) return res.cc(err)

            db.query(`insert into addorder (name,imgUrl,state) values ('${orderName}','${orderImgurl}','${orderState}')`, function (err, result) {
                db.query(`select * from addorder`, function (err, result) {

                })
            })
        })
    })
}
// 获取结算列表
exports.orderList = (req, res) => {

    db.query('select * from addorder', req.params.id, (err, results) => {
        // if (err) return res.cc(err)

        res.send({
            status: 0,
            message: '查询结算列表成功',
            data: results

        })
    })
}
// 提交订单处理函数
exports.submitOrder = (req, res) => {
    let submitList = Object.keys(req.body)

    let orderId = ''
    const shopId = []
    submitList.forEach(v => {
        v = JSON.parse(v)
        console.log(v);
        orderId = v.orderId
        v.goodsList.forEach(v => {
            shopId.push(JSON.parse(v.id))

        })

    })
    // console.log(orderId);
    db.query(`select * from submitorder where orderId = ${orderId}`, function (err, result) {
        // console.log(result);
        //订单的数据库id
        let id = ''
        result = JSON.parse(JSON.stringify(result))
        result.forEach(v => {
            id = v.id
        })

        //修改订单状态 1==>2
        db.query(`update submitorder set state = replace(state,'1','2') where id = ${id}`, function (e, r) {
            //购物车数据删除
            shopId.forEach(v => {
                db.query(`delete from goods_cart where id = ${v}`, function () {

                })
            })
            res.send({
                data: {
                    code: 200,
                    success: true
                }
            })
        })
    })


},
    // 查询订单
    exports.selectOrder = (req, res) => {
        //接收前端给后端的订单号
        let orderId = JSON.parse(Object.keys(req.body)).orderId
        db.query(`select * from submitorder where orderId=${orderId}`, function (err, result) {
            res.send({
                data: {
                    success: true,
                    code: 200,
                    data: result
                }
            })
        })

    }
//  发起支付
exports.payMent = (req, res) => {
    // 订单号
    let orderId = req.body.orderId;
    //商品总价
    let price = req.body.price;
    //购买商品的名称
    let name = req.body.name;

    //开始对接支付宝API
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    //支付时信息
    formData.addField('bizContent', {
        outTradeNo: orderId,//订单号
        productCode: 'FAST_INSTANT_TRADE_PAY',//写死的
        totalAmount: price,//价格
        subject: name,//商品名称


    });
    //支付成功或者失败跳转的链接
    formData.addField('returnUrl', 'http://localhost:8080/#/payment');
    //返回promise
    const result = alipaySdk.exec(
        'alipay.trade.page.pay',
        {},
        { formData: formData },
    );
    //对接支付宝成功，支付宝方返回的数据
    result.then(resp => {
        // 返回的paymentUrl就是前端要打开的支付地址
        res.send({
            data: {
                code: 200,
                success: true,
                msg: '支付中',
                paymentUrl: resp
            }
        })
    })
}
// 支付状态
exports.successPayment = (req, res) => {
    //订单号
    let out_trade_no = req.body.out_trade_no;
    let trade_no = req.body.trade_no;
    //支付宝配置
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    //支付时信息
    formData.addField('bizContent', {
        out_trade_no,
        trade_no
    });
    //返回promise
    const result = alipaySdk.exec(
        'alipay.trade.query',
        {},
        { formData: formData },
    );

    //后端请求支付宝
    result.then(resData => {
        axios({
            method: 'GET',
            url: resData
        }).then(data => {
            let responseCode = data.data.alipay_trade_query_response;
            if (responseCode.code == '10000') {
                switch (responseCode.trade_status) {
                    case 'WAIT_BUYER_PAY':
                        res.send({
                            data: {
                                code: 0,
                                data: {
                                    msg: '支付宝有交易记录，没付款'
                                }
                            }
                        })
                        break;

                    case 'TRADE_CLOSED':
                        res.send({
                            data: {
                                code: 1,
                                data: {
                                    msg: '交易关闭'
                                }
                            }
                        })
                        break;

                    case 'TRADE_SUCCESS':

                        db.query(`select * from submitorder where orderId = ${out_trade_no}`, function (err, result) {
                            let id = result[0].id;
                            //订单的状态修改掉2==》3
                            db.query(`update submitorder set state = replace(state,'2','3') where id = ${id}`, function () {
                                res.send({
                                    data: {
                                        code: 2,
                                        data: {
                                            msg: '交易完成'
                                        }
                                    }
                                })
                            })
                        })
                        break;
                }
            } else if (responseCode.code == '40004') {
                res.send({
                    data: {
                        code: 4,
                        msg: '交易不存在'
                    }
                })
            }
        }).catch(err => {
            res.send({
                data: {
                    code: 500,
                    msg: '交易失败',
                    err
                }
            })
        })
    })
}
// 待付款
exports.noPayment = (req, res) => {
    db.query(`select * from submitorder where state=2`, function (err, result) {
        // console.log(result);
        res.send({
            data: {
                success: true,
                code: 200,
                data: result
            }
        })
    })
}
// 已付款
exports.yiPayment = (req, res) => {
    db.query(`select * from submitorder where state=3`, function (err, result) {
        res.send({
            data: {
                success: true,
                code: 200,
                data: result
            }
        })
    })
}




